package algotithm.leetcode.stack.test20;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author 25068
 * @Date 2021/4/20 11:55
 * @Title 20. 有效的括号
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        String s = "()[]{}";
        boolean flag = solution.isValid(s);
        System.out.println(flag);
    }

    public boolean isValid(String s) {
        if (s.length() % 2 == 0) {
            Deque<Character> stack = new ArrayDeque<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == '(' || c == '[' || c == '{') {
                    stack.push(c);
                } else if (c == ')') {
                    if (!stack.isEmpty() && stack.peek() == '(') {
                        stack.pop();
                    } else {
                        return false;
                    }
                } else if (c == ']') {
                    if (!stack.isEmpty() && stack.peek() == '[') {
                        stack.pop();
                    } else {
                        return false;
                    }
                } else if (c == '}') {
                    if (!stack.isEmpty() && stack.peek() == '{') {
                        stack.pop();
                    } else {
                        return false;
                    }
                }

            }
            return stack.isEmpty();
        }
        return false;
    }
}
